#!/bin/sh
  set -e

  export LC_ALL=en_US.UTF-8
  export SECRET_KEY_BASE=GENERATED_CODE

  export SUBMAIL_MESSAGE_KEY="b99d9efde5dabc6a2c308cc2ff6bf3f5"
  export SUBMAIL_MESSAGE_ID="12462"
  export SUBMAIL_MAIL_ID="11957"
  export SUBMAIL_MAIL_KEY="95f73c8243ec44cf578e913e80cfc7cb"

  export QINIU_ACCESS_KEY="D2HoWxWkb2MHhZVO5J5902DyeGNA05csQJOomlg0"
  export QINIU_SECRET_KEY="TmrvwiSTzBO9snZ2dg8JOYuCQA19IetyN-gZpZT8"
  export QINIU_BUCKET="test-yangyi-web"

  export PINGXX_ID="app_80qvD0eDSKWPCyj5"
  export PINGXX_API_KEY="sk_live_v5Sm5OOinjDGKS0e1CyPifLO"

  #other env variables here

  RBENV_ROOT="/home/tim/.rbenv"
  PATH="$RBENV_ROOT/bin:$RBENV_ROOT/shims:$PATH"
  TIMEOUT=60
  APP_ROOT="/home/tim/app/current"
  PID="/home/tim/app/shared/tmp/pids/unicorn.pid"
  ENVIRONMENT="production"
  CONFIG="/home/tim/app/current/config/unicorn/production.rb"
  # CMD="cd $APP_ROOT && rvm use 1.9.3 && /usr/local/bin/unicorn_rails -D -c $APP_ROOT/$CONFIG -E $ENVIRONMENT"
  # CMD="bundle exec unicorn -D -c $APP_ROOT/$CONFIG -E $ENVIRONMENT"
  # CMD="$APP_ROOT/bin/unicorn -D -c $APP_ROOT/$CONFIG -E $ENVIRONMENT"
  UARGS="-D -c $CONFIG -E $ENVIRONMENT"
  CMD="bundle exec unicorn_rails $UARGS"
  action="$1"
  #set -u

  cd $APP_ROOT || exit 1

  old_pid="$PID.oldbin"

  # cd $APP_ROOT || exit 1

  sig () {
    test -s "$PID" && kill -$1 `cat $PID`
  }

  oldsig () {
    test -s $old_pid && kill -$1 `cat $old_pid`
  }

  workersig () {
    workerpid="$APP_ROOT/tmp/pids/unicorn.$2.pid"
    test -s "$workerpid" && kill -$1 `cat $workerpid`
  }

  case $action in
  start)
    sig 0 && echo >&2 "Already running" && exit 0
    $CMD && echo "start ok" && exit 0
    ;;
  stop)
    sig QUIT && echo "stop ok" && exit 0
    echo >&2 "Not running"
    ;;
  force-stop)
    sig TERM && echo "force-stop ok" && exit 0
    echo >&2 "Not running"
    ;;
  restart|reload)
    sig HUP && echo "reloaded OK" && exit 0
    echo >&2 "Couldn't reload, starting '$CMD' instead"
    $CMD
    ;;
  upgrade)
    sig USR2 && echo Upgraded && exit 0
    echo >&2 "Couldn't upgrade, starting '$CMD' instead"
    $CMD
    ;;
  # upgrade)
  #   if sig USR2 && sleep 2 && sig 0 && oldsig QUIT
  #   then
  #     n=$TIMEOUT
  #     while test -s $old_pid && test $n -ge 0
  #     do
  #       printf '.' && sleep 1 && n=$(( $n - 1 ))
  #     done
  #     echo
  #
  #     if test $n -lt 0 && test -s $old_pid
  #     then
  #       echo >&2 "$old_pid still exists after $TIMEOUT seconds"
  #       exit 1
  #     fi
  #     exit 0
  #   fi
  #   echo >&2 "Couldn't upgrade, starting '$CMD' instead"
  #   su -c "$CMD" - vagrant
  #   ;;
  kill_worker)
    workersig QUIT $2 && exit 0
    echo >&2 "Worker not running"
    ;;

  reopen-logs)
    sig USR1
    ;;
  *)
    echo >&2 "Usage: $0 <start|stop|restart|upgrade|force-stop|reopen-logs>"
    exit 1
    ;;
  esac





